<template>
  <div class="login_box">
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="qqq"
        label="用户名"
        placeholder="用户名"
        :rules="[
        { required: true, message: '请填写用户名'},
        {pattern:/^\d{11}$/,message:'请输入正确的手机号'}
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="www"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">{{isLogin ? '登录' : '注册'}}</van-button>
      </div>
    </van-form>

    <van-button>{{isLogin ? "立即注册" : "已有帐号直接登录"}}</van-button>
  </div>
</template>

<script>
// 导入封装的login方法
import api from "../api/index";
import md5 from "md5";
export default {
  data() {
    return {
      username: "",
      password: "",
      isLogin: true // 控制当前是登录还是注册
    };
  },
  methods: {
    onSubmit(values) {
      // 能执行 说明 校验规则已经通过了
      if (this.isLogin) {
        console.log("submit", values);
        api
          .login({
            // 这两个属性名是后台要求的属性名
            loginName: this.username,
            passwordMd5: md5(this.password)
          })
          .then(data => {
            if (data.code == 200) {
              localStorage.setItem("shop_token", data.data);
              this.$store.commit("updateToken", data.data); // 把token存储到vuex中
              // this.$router.replace("/home");
              if (this.$route.query.canback) {
                this.$router.back();
              } else {
                this.$router.replace("/");
              }
            }
          });
      } else {
        // 证明是注册
        api
          .register({
            // 这两个属性名是后台要求的属性名
            loginName: this.username,
            password: this.password
          })
          .then(data => {
            console.log(data);
          });
      }
    }
  }
};
</script>

<style lang="less" scoped>
.login_box {
  padding-top: 100px;
}
</style>